<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Configs extends BaseModel
{
    protected $table = 'configs';
    //主键ID
    protected $primaryKey = 'id';
    //是否允许批量修改
    protected $fillable = ['name', 'value'];
    private static $config = [
        'cache_key' => 'config_',//缓存前缀
    ];

    /**
     * 获取缓存
     * @param $name
     * @param string $default
     * @return mixed
     */
    public static function getValue($name, $default = '')
    {
        $expired = Carbon::now()->addDay(1);
        $key     = self::$config['cache_key'] . $name;
        return Cache::remember($key, $expired, function () use ($name, $default) {
            return self::where('name', $name)->value('value') ?: $default;
        });
    }

    /**
     * 清理缓存
     * @param $name
     * @return bool
     */
    public static function clean($name)
    {
        $key = self::$config['cache_key'] . $name;
        if (Cache::has($key)) {
            return Cache::forget($key);
        }
        return false;
    }
}